import store from 'react-native-simple-store';
import { NativeModules } from 'react-native';
const DeviceInfo = require('react-native-device-info');
const sha1 = require('sha1');
const ReactAES = NativeModules.ReactAES;
import { getJson } from './JsonUtil'

export const getEncryptedToken = (chiper, key, iv) => {
  return new Promise((resolve, reject) => {
    let resolveData;
    ReactAES.decrypt(chiper, key, iv).then((decrypted) => {
      const tokenData = getJson(decrypted); 
      if (tokenData) {
        const { token } = tokenData;
        resolve(token);
      } else {
        reject();
      }
    });
  });
}

export const getEncryptedData = (storeKey, key, iv) => {
  return store.get(storeKey).then(chiper => {
      return new Promise((resolve, reject) => {
        ReactAES.decrypt(chiper, key, iv).then((decrypted) => {
          const tokenData = getJson(decrypted); 
          if (tokenData) {
            resolve(tokenData);
          } else {
            reject();
          }
        })
      })    
    }
  );
}

export const getSignatureDataFromStore = (storeKey, key, iv) => {
  return new Promise((resolve, reject) => {
    store.get(storeKey).then(chiper => {
      ReactAES.decrypt(chiper, key, iv).then((decrypted) => {
        const userInfo = getJson(decrypted);
        if (userInfo) {
          const {uim, deviceToken, suid, site_id} = userInfo;
          const timeStamp = Math.floor(Date.now() / 1000);
          const tmpArr = [uim, deviceToken, timeStamp, DeviceInfo.getUniqueID()].sort();
          const signature = sha1(tmpArr.join(''));
          resolve({
            site_id: site_id, 
            uim: uim, 
            suid: suid, 
            timeStamp: timeStamp, 
            signature: signature
          })
        } else {
          reject()
        }
      });
    })
  })
}

export const getEncryptedTokenFromStore = (storeKey, key, iv) => 
  store.get(storeKey).then(chiper => getEncryptedToken(chiper, key, iv))

export const refactTokenToAuthData = (storeKey, chiper, key, iv) => {
  let token;
  return new Promise((resolve, reject) => {
    getEncryptedToken(chiper, key, iv)
    .then(decrypted => (token = decrypted) && store.get(storeKey))
    .then(userChiper => ReactAES.decrypt(userChiper, key, iv))
    .then(userDecrypted => refactToken(userDecrypted, token))
    .then(authUserInfo => ReactAES.encrypt(JSON.stringify(authUserInfo), key, iv))
    .then(encryptedAuthData => store.save(storeKey, encryptedAuthData))
    .then(result => resolve(token));
  }) 
}

export const refactToken = (userDecrypted, token) => {
  return new Promise((resolve, reject) => {
    let authUserInfo = getJson(userDecrypted)
    if (authUserInfo) {
      authUserInfo.token = token;
      resolve(authUserInfo)
    } else {
      reject();
    }
  })
}


